package com.promise.jokerdream.work.signin.after

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.utils.AppContext

// 日常任务工作
class PenguinTaskWork(override val uin: String): BaseWork(uin) {
    
    override val name: String
        get() = "日常任务"

    override val priority: Int
        get() = 6
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询企鹅任务
            val queryResult = gameApi.queryPenguinTask(uin)
            
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    // 根据任务状态判断是否领取奖励
                    response.tasklist.forEach { task ->
                        if (task.status == 3) { // 3表示已完成但未领取
                            val rewardResult = gameApi.rewardPenguinTask(uin, task.id)
                            rewardResult.foldWithApiException(
                                onSuccess = { rewardResponse ->
                                    historyManager.addHistory(name, rewardResponse.getDescription())
                                },
                                onFailure = { code, msg ->
                                    historyManager.addHistory(name, msg, code)
                                }
                            )
                        }
                    }
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}